<template>
  <div class="system-roles">
    <div class="page-header">
      <h1 class="page-title">角色管理</h1>
      <el-button
        type="primary"
        @click="handleAddRole"
        v-permission="'system:role:add'"
      >
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <el-card>
      <el-table :data="roleList" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column
          prop="description"
          label="描述"
          show-overflow-tooltip
        />
        <el-table-column prop="permissions" label="权限数量">
          <template #default="{ row }">
            <el-tag>{{ row.permissions?.length || 0 }} 个权限</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === true ? 'success' : 'warning'">
              {{ row.status === true ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                size="small"
                type="primary"
                @click="handleEditRole(row)"
                v-permission="'system:role:edit'"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="handleAssignPermissions(row)"
                v-permission="'system:role:assign'"
              >
                分配权限
              </el-button>
              <el-button
                size="small"
                type="danger"
                plain
                @click="handleDeleteRole(row)"
                :disabled="row.code === 'super_admin'"
                v-permission="'system:role:delete'"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEditMode ? '编辑角色' : '新增角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input
            v-model="roleForm.code"
            placeholder="请输入角色编码"
            :disabled="isEditMode"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">
            {{ isEditMode ? "保存" : "创建" }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="分配权限" width="60%">
      <div class="permission-assign">
        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTreeData"
            :props="{ children: 'children', label: 'name' }"
            show-checkbox
            node-key="id"
            :default-checked-keys="selectedPermissions"
            @check="handlePermissionCheck"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import request from "../../utils/request";

// 响应式数据
const loading = ref(false);
const roleList = ref([]);
const permissionDialogVisible = ref(false);
const permissionTreeData = ref([]);
const selectedPermissions = ref([]);
const currentRole = ref(null);
const permissionTreeRef = ref();

// 角色编辑相关
const roleDialogVisible = ref(false);
const isEditMode = ref(false);
const roleFormRef = ref();
const roleForm = ref({
  name: "",
  code: "",
  description: "",
  status: true,
});

const roleRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
  description: [
    { max: 200, message: "描述不能超过 200 个字符", trigger: "blur" },
  ],
};

// 获取角色列表
const getRoleList = async () => {
  try {
    loading.value = true;
    const response = await request({
      url: "/jjx/roles",
      method: "GET",
    });
    if (response.success) {
      roleList.value = response.data;
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取权限列表
const getPermissionList = async () => {
  try {
    const response = await request({
      url: "/jjx/permissions",
      method: "GET",
    });
    if (response.success) {
      // 将权限按模块分组，构建树形结构
      const permissions = response.data;
      const moduleMap = new Map();

      permissions.forEach((permission) => {
        if (!moduleMap.has(permission.module)) {
          moduleMap.set(permission.module, {
            id: permission.module,
            name: getModuleName(permission.module),
            children: [],
          });
        }

        // 只添加非菜单类型的权限（操作权限）
        if (permission.type !== "menu" || permission.code.includes(":")) {
          moduleMap.get(permission.module).children.push({
            id: permission._id,
            name: permission.name,
            code: permission.code,
            type: permission.type,
          });
        }
      });

      permissionTreeData.value = Array.from(moduleMap.values());
    }
  } catch (error) {
    console.error("获取权限列表失败:", error);
  }
};

// 获取模块名称
const getModuleName = (module: string) => {
  const moduleNames = {
    system: "系统管理",
    doctor: "医生管理",
    patient: "患者管理",
    appointment: "预约管理",
    finance: "财务管理",
  };
  return moduleNames[module] || module;
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 重置表单
const resetRoleForm = () => {
  roleForm.value = {
    name: "",
    code: "",
    description: "",
    status: true,
  };
  roleFormRef.value?.clearValidate();
};

// 新增角色
const handleAddRole = () => {
  isEditMode.value = false;
  resetRoleForm();
  roleDialogVisible.value = true;
};

// 编辑角色
const handleEditRole = (role: any) => {
  isEditMode.value = true;
  roleForm.value = {
    id: role._id,
    name: role.name,
    code: role.code,
    description: role.description || "",
    status: role.status,
  };
  roleDialogVisible.value = true;
};

// 保存角色
const handleSaveRole = async () => {
  try {
    await roleFormRef.value.validate();

    const roleData = {
      name: roleForm.value.name,
      code: roleForm.value.code,
      description: roleForm.value.description,
      status: roleForm.value.status,
    };

    let response;
    if (isEditMode.value) {
      response = await request({
        url: `/jjx/roles/${roleForm.value.id}`,
        method: "PUT",
        data: roleData,
      });
    } else {
      response = await request({
        url: "/jjx/roles",
        method: "POST",
        data: roleData,
      });
    }

    if (response.success) {
      ElMessage.success(isEditMode.value ? "编辑角色成功" : "新增角色成功");
      roleDialogVisible.value = false;
      getRoleList(); // 刷新列表
    }
  } catch (error) {
    console.error("保存角色失败:", error);
  }
};

// 分配权限
const handleAssignPermissions = async (role: any) => {
  currentRole.value = role;
  selectedPermissions.value = role.permissions?.map((p) => p._id || p.id) || [];
  permissionDialogVisible.value = true;

  // 获取权限列表
  if (permissionTreeData.value.length === 0) {
    await getPermissionList();
  }
};

// 权限选择变化
const handlePermissionCheck = () => {
  // 处理权限选择逻辑
};

// 保存权限分配
const handleSavePermissions = async () => {
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys();
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
    const allSelectedKeys = [...checkedKeys, ...halfCheckedKeys];

    // 过滤掉模块名称，只保留有效的ObjectId
    // ObjectId是24位的十六进制字符串
    const validPermissionIds = allSelectedKeys.filter((key) => {
      return typeof key === "string" && /^[a-fA-F0-9]{24}$/.test(key);
    });

    console.log("原始选中的键值:", allSelectedKeys);
    console.log("过滤后的权限ID:", validPermissionIds);

    const response = await request({
      url: `/jjx/roles/${currentRole.value._id}`,
      method: "PUT",
      data: {
        permissions: validPermissionIds,
      },
    });

    if (response.success) {
      ElMessage.success("权限分配成功");
      permissionDialogVisible.value = false;
      getRoleList(); // 刷新列表
    }
  } catch (error) {
    console.error("保存权限失败:", error);
    ElMessage.error("权限分配失败，请重试");
  }
};

// 删除角色
const handleDeleteRole = async (role: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？此操作不可恢复。`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await request({
      url: `/jjx/roles/${role._id}`,
      method: "DELETE",
    });

    if (response.success) {
      ElMessage.success("删除成功");
      getRoleList(); // 刷新列表
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除角色失败:", error);
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  getRoleList();
});
</script>

<style lang="scss" scoped>
.system-roles {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .permission-assign {
    .permission-tree {
      max-height: 400px;
      overflow-y: auto;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 12px;
    }
  }

  .operation-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;

    .el-button {
      margin: 2px 0;
      min-width: 60px;

      &.is-disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      &[type="danger"][plain] {
        border-color: #f56c6c;
        color: #f56c6c;

        &:hover:not(.is-disabled) {
          background-color: #f56c6c;
          color: white;
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>